package com.njym.test;

import org.junit.Test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhy
 * 线程交替执行
 * @date 2020-04-02 13:16
 **/
public class ThreadTest3 {
	static char[] numArray = "123456".toCharArray();

	static char[] alphArray = "ABCDEF".toCharArray();

	volatile static int flag = 1;

	static Object o = new Object();

	public static void main(String[] args) {
		new Thread(() -> {
			synchronized (o) {
				for (char chaer : alphArray) {
					while (flag != 2) {
						try {
							o.wait();
						}
						catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(chaer);
					flag = 1;
					o.notify();
					//					try {
					//						o.wait();
					//					}
					//					catch (InterruptedException e) {
					//						e.printStackTrace();
					//					}
				}
			}
		}, "t2").start();

		new Thread(() -> {
			synchronized (o) {
				for (char chaer : numArray) {
					while (flag != 1) {
						try {
							o.wait();
						}
						catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					flag = 2;
					System.out.println(chaer);
					o.notify();
					//					try {
					//						o.wait();
					//					}
					//					catch (InterruptedException e) {
					//						e.printStackTrace();
					//					}
				}
				//				o.notify();
			}
		}, "t1").start();
	}

	static Lock lock = new ReentrantLock();

	static Condition condition1 = lock.newCondition();

	static Condition condition2 = lock.newCondition();

	volatile static int status = 1;

	@Test
	public void main3() {
		new Thread(() -> {
			lock.lock();
			try {
				for (char c : numArray) {
					while (status != 1) {
						try {
							condition1.await();
						}
						catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(c);
					status = 2;
					condition2.signal();
				}
			}
			finally {
				lock.unlock();
			}
		}, "t1").start();

		new Thread(() -> {
			lock.lock();
			try {
				for (char c : alphArray) {
					while (status != 2) {
						try {
							condition2.await();
						}
						catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(c);
					status = 1;
					condition1.signal();
				}
			}
			finally {
				lock.unlock();
			}
		}, "t2").start();
	}

	Thread t1;
	Thread t2;
	@Test
	public void main2() {

		t1 = new Thread(() -> {
			for (char c : numArray) {
				System.out.println(c);
				LockSupport.unpark(t2);
				LockSupport.park();
			}
		});

		t2 = new Thread(() -> {
			for (char c : alphArray) {
				LockSupport.park();
				System.out.println(c);
				LockSupport.unpark(t1);

			}
		});
		t1.start();
		t2.start();
	}
}
